/*
 * Copyright (C) 2011 Mette Bank, Rikke Jensen, Kenneth Brodersen, Thomas Pedersen
 * 
 * This file is part of digiPECS.
 * 
 * digiPECS is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * digiPECS is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with digiPECS.  If not, see <http://www.gnu.org/licenses/>.
 */

package sw6.digipecs.helpers;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import sw6.digipecs.user.MainActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Environment;

public class DigiLoader {
	public static final String HAS_RUN = "hasRun"; 
	public static final String EXTERNAL_PATH = Environment.getExternalStorageDirectory().getPath(); 
	public static final String PECS_DIR_NAME = "PECS";
	public static final String PECS_DIR_PATH = Environment.getExternalStorageDirectory().getPath() + "/" + PECS_DIR_NAME;
	public static final String TAG="DigiLoader"; 
	
	private static final String PREF_FIRSTRUN = "firstRun"; 
	private static final String ZIP_NAME = "pictures.zip"; 
	private static final String XML_FILE_NAME = "pictures.xml"; 
	
	static SharedPreferences mPrefs;
	private static Context mContext;
	private static String mZipDirectoryPath;
	private static File mZipFile;
	private static Activity mActivity;
	
	public static void Load(Context context, Activity activity)
	{
		mActivity = activity; 
		mContext = context; 
		mPrefs = mContext.getSharedPreferences("loader", Context.MODE_WORLD_WRITEABLE); 	
		boolean isFirstRun = isThisFirstRun(); 
		if(isFirstRun)
		{
			boolean isPackageFound = CheckForImagePackage(); 
			if(isPackageFound)
			{
				showImportDialog(); 
			}
		}
	}
	
	private static void showImportDialog() {
		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
		        switch (which){
		        case DialogInterface.BUTTON_POSITIVE:
		            importPictures(); 
		            if(mActivity!=null)
		            {
		            	mActivity.finish(); 
		            	Intent intent = new Intent(mContext,MainActivity.class); 
		            	mContext.startActivity(intent); 
		            }
		            break;

		        case DialogInterface.BUTTON_NEGATIVE:
		            break;
		        }
		    }
		};

		AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
		builder.setMessage("zip fil fundet, vil du importere billeder?").setPositiveButton("Ja", dialogClickListener)
		    .setNegativeButton("Nej", dialogClickListener).show();
	}
	
	private static void deleteDir(File file) {
		if (file.isDirectory()) for (File f : file.listFiles()) deleteDir(f);
		file.delete();
	}
	
	private static void importPictures()
	{
		File zipDirectory = new File(mZipDirectoryPath); 
		if(zipDirectory.exists()) deleteDir(zipDirectory);
		zipDirectory.mkdirs();
		
		//Lets unzip the content
		unzip(mZipFile.getPath(), mZipDirectoryPath+"/"); 
		//Ok lets see if there is a xml file
		File xmlFile = new File(mZipDirectoryPath+"/"+XML_FILE_NAME); 
		boolean exsists = xmlFile.exists(); 
		if(exsists)
		{
			PictureParser parser = new PictureParser(mContext,xmlFile); 
			parser.parse(); 
		}
	}

	private static boolean CheckForImagePackage() {
		mZipFile = new File(EXTERNAL_PATH+"/"+ZIP_NAME); 
		mZipDirectoryPath = PECS_DIR_PATH+"/zip"; 
		return mZipFile.exists(); 
	}

	private static boolean isThisFirstRun()
	{
		boolean firstRun = getFirstRun();  
		if(firstRun)
		{
			setFirstRun();
		}
		return firstRun; 
	}
	
	private static void setFirstRun() {
		SharedPreferences.Editor editor = mPrefs.edit(); 
		editor.putBoolean(PREF_FIRSTRUN, false); 
		editor.commit(); 
	}
	public static boolean getFirstRun()
	{
		return mPrefs.getBoolean(PREF_FIRSTRUN, true); 
	}
	
	public static File getFile(Context context, String dir, String fn) throws IOException {
		File file = new File(DigiLoader.PECS_DIR_PATH + "/" + fn);
		
		// Insure that the directories are created
		if (!file.getParentFile().exists()) {
			if (!file.mkdirs()) {
				throw new IOException("Directory could not be created");
			}
		}
		
		return file;
	}
	 private static void unzip(String src, String dest){
		  
		  final int BUFFER_SIZE = 4096;
		  
		  BufferedOutputStream bufferedOutputStream = null;
		     FileInputStream fileInputStream;
		     try {
		      fileInputStream = new FileInputStream(src);
		      ZipInputStream zipInputStream 
		       = new ZipInputStream(new BufferedInputStream(fileInputStream));
		      ZipEntry zipEntry;
		      
		      while ((zipEntry = zipInputStream.getNextEntry()) != null){
		       
		       String zipEntryName = zipEntry.getName();
		       File file = new File(dest + zipEntryName);
		       
		       if (file.exists()){
		        
		       } else {
		        if(zipEntry.isDirectory()){
		         file.mkdirs(); 
		        }else{
		         byte buffer[] = new byte[BUFFER_SIZE];
		         FileOutputStream fileOutputStream = new FileOutputStream(file);
		         bufferedOutputStream 
		          = new BufferedOutputStream(fileOutputStream, BUFFER_SIZE);
		         int count;

		         while ((count 
		          = zipInputStream.read(buffer, 0, BUFFER_SIZE)) != -1) {
		          bufferedOutputStream.write(buffer, 0, count);
		         }

		         bufferedOutputStream.flush();
		         bufferedOutputStream.close(); 
		        }
		       } 
		      }
		      zipInputStream.close();
		     } catch (FileNotFoundException e) {
		      // TODO Auto-generated catch block
		      e.printStackTrace();
		     }catch (IOException e) {
		      // TODO Auto-generated catch block
		      e.printStackTrace();
		     }
		 }
}
